package framework.view;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import framework.utils.*;
import framework.utils.dto.*;
import framework.controller.*;
import framework.model.*;

public class ChallengesView extends InteractiveView {

	private JLabel challengeLabel;
	private JScrollPane challengeScrollPane;
	private JPanel challengesPanel;
	private JButton challengeClearButton;
	
	/**********************
	 *** GLOBAL METHODS ***
	 *********************/
	
	public ChallengesView(LobbyModel model, LobbyController controller) {
		super(model, controller);
		this.init();
		super.add(this.challengeLabel, BorderLayout.NORTH);
		super.add(this.challengeScrollPane, BorderLayout.CENTER);
		super.add(this.challengeClearButton, BorderLayout.SOUTH);
	};
	
	private void init() {
		// Container
		super.setLayout(new BorderLayout(0,0));
		//Challenge label
		this.challengeLabel = new JLabel("Challenges:");
		this.challengeLabel.setPreferredSize(new Dimension(600,30));
		//Clear button
		this.challengeClearButton = new JButton("clear challenges");
		this.challengeClearButton.setActionCommand("clear");
		this.challengeClearButton.addActionListener(this);
		//Challenges Panel
		this.challengesPanel = new JPanel(new WrapLayout(0,0,0));
		this.setChallengeScrollPane();
	};
	
	@Override
	public void actionPerformed(ActionEvent e) {
		switch(e.getActionCommand()) {
			case "challenge_updated" :
				this.handleChallengeUpdatedResponse();
			break;
			case "clear" :
				this.getController().handleChallengeRemoveAllRequest();
			break;
			case "game_updated" :
				if(this.getModel().isInGame()) {
					SwingUtilities.getWindowAncestor(this).dispose();
				}
			break;
		};
	};
	
	/**********************
	 *** SETTER METHODS ***
	 *********************/
	
	private void setChallengeScrollPane() {
		//ScrollPane
		this.challengeScrollPane = new JScrollPane(
			JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
		);
		//Add challenges panel
		this.challengeScrollPane.setViewportView(this.challengesPanel);
	};
	
	/**********************
	 *** GETTER METHODS ***
	 *********************/
	
	@Override
	protected LobbyController getController() {
		return (LobbyController)super.getController();
	};
	
	@Override
	protected LobbyModel getModel() {
		return (LobbyModel)super.getModel();
	};
	
	/**********************
	 *** HANDLE METHODS ***
	 *********************/
	
	private void handleChallengeUpdatedResponse() {
		//Remove all challenges from panel
		this.challengesPanel.removeAll();
		//Add challenges to panel
		for(Challenge challenge : this.getModel().getChallenges()) {
			this.challengesPanel.add(new ChallengeView(
				this.getModel(), this.getController(), challenge
			));	
		}
		//Repaint view
		this.validate();
		this.repaint();
	};

}
